package study.kits.excel.easyexcel.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import study.kit.eggs.result.Result;
import study.kit.eggs.result.Results;
import study.kits.excel.easyexcel.service.easyexcel.excel.ExcelExportData;
import study.kits.excel.easyexcel.service.easyexcel.excel.ExcelImportData;
import study.kits.excel.easyexcel.service.easyexcel.excel.MyDataListener;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/easyExcel")
public class EasyExcelController {

    /**
     * 导入
     */
    @PostMapping("/import")
    public Result importExcel(@RequestParam MultipartFile file) {
        // 验参

        // 解析
        try (InputStream is = file.getInputStream()) {
            MyDataListener listener = new MyDataListener();
            EasyExcel.read(is, ExcelImportData.class, listener)
                    .sheet()
                    .doRead();

        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
        return Results.ok();
    }

    /**
     * 通过 write 方式导出
     */
    @PostMapping("/exportByWrite")
    public Result exportByWrite(HttpServletResponse response) {
        //
        List<ExcelExportData> dataLt = Arrays.asList(ExcelExportData.builder()
                        .name("张三")
                        .build(),
                ExcelExportData.builder()
                        .name("李四")
                        .build());
        // 文件名
        String fileName = "这是一个测试.xlsx";
//                       response.setContentType("application/octet-stream");
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // 响应参数
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLUtil.encode(fileName));
        // 输出
        try (OutputStream out = response.getOutputStream()) {
            //
            EasyExcel.write(out, ExcelExportData.class)
                    .sheet("模板")
                    .doWrite(dataLt);
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }

        return Results.ok();
    }

    /**
     * 通过 fill 方式导出
     */
    @PostMapping("/exportByFill")
    public Result exportByFill(HttpServletResponse response) {
        //
        Map<String, Object> data = MapUtil.ofEntries(
                MapUtil.entry("activityName", "王昭君"),
                MapUtil.entry("siteName", "anyang")
        );
        //
        List<Map<String, ?>> dataLt = Arrays.asList(
                MapUtil.ofEntries(
                        MapUtil.entry("stuName", "张三"),
                        MapUtil.entry("stuCode", "10001"),
                        MapUtil.entry("subjectCodes", "YY,SX,YW")
                ),
                MapUtil.ofEntries(
                        MapUtil.entry("stuName", "李四"),
                        MapUtil.entry("stuCode", "10002"),
                        MapUtil.entry("subjectCodes", "YY,SX,YW")
                )
        );
        //
        try (OutputStream out = response.getOutputStream();
             InputStream tplIn = ResourceUtil.getStream("tpl/enroll_stu_sheet.xlsx")) {
            //
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + "sadf" + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "fffffffff" + ".xlsx");
            //
            ExcelWriter writer = EasyExcel.write(out)
                    .withTemplate(tplIn)
                    .build();
            //工作簿
            WriteSheet sheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder()
                    .forceNewRow(Boolean.TRUE)
                    .build();
            //明细
            writer.fill(dataLt, fillConfig, sheet);
            writer.fill(data, fillConfig, sheet);

            //TODO 不执行该方法，生成文件打不开
            writer.finish();
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
        //TODO 此处返回对象，导出 excel 报错
        return Results.ok();
    }
}
